<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="标题" prop="questionTitle">
        <el-input v-model="form.questionTitle" placeholder="请输入题目标题"/>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="题型" prop="questionType">
            <el-select
              v-model="form.questionType"
              placeholder="请选择题型"
              @change="handleQuestionTypeChange"
            >
              <el-option
                v-for="dict in dict.type.bis_question_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="难度" prop="difficulty">
            <el-select v-model="form.difficulty" placeholder="请选择难度">
              <el-option
                v-for="dict in dict.type.bis_question_difficulty"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="题干" prop="questionText">
        <editor v-model="form.questionText" ref="questionEditorComponent"/>
      </el-form-item>

      <el-form-item label="答案" prop="options" v-if="showOptionsArea">
        <div class="options-container">
          <component
            ref="questionComponent"
            :is="questionTypeComponent"
            :options="dynamicOptions"
            :correctAnswer="correctAnswer"
            @updateOptions="updateOptions"
            @updateCorrectAnswer="updateCorrectAnswer"
            @removeOption="removeOption"
            @input="handleEssayAnswerChange"
          />
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addOption"
            style="margin-top: 10px"
            v-if="showInputArea"
          >
            添加输入框
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <input-and-search-with-tree
          ref="categoryTree"
          v-model="form.categoryId"
          @change="handleCategoryChange"
        />
      </el-form-item>

      <el-form-item label="知识点" prop="pointId">
        <input-and-search-with-list
          ref="pointSelect"
          v-model="form.pointId"
          :categoryId="form.categoryId"
          @change="handlePointChange"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addQuestions, updateQuestions, getQuestions } from "@/api/question/manage";
import { getFilesByIds } from '@/api/files/file'
import InputAndSearchWithTree from "@/components/InputAndSearchWithTree/index.vue";
import InputAndSearchWithList from "@/components/InputAndSearchWithList/index.vue";
import SingleChoice from "@/components/question/SingleChoice/index.vue";
import MultipleChoice from "@/components/question/MultipleChoice/index.vue";
import FillInBlank from "@/components/question/FillInBlank/index.vue";
import TrueFalse from "@/components/question/TrueFalse/index.vue";
import EssayQuestion from "@/components/question/EssayQuestion/index.vue";

export default {
  name: "QuestionInput",
  components: {
    InputAndSearchWithList,
    InputAndSearchWithTree,
    SingleChoice,
    MultipleChoice,
    FillInBlank,
    TrueFalse,
    EssayQuestion,
  },
  dicts: ['bis_question_type', 'bis_question_difficulty'],
  props: {
    questionId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      form: {
        questionId: null,
        questionTitle: null,
        questionText: null,
        questionTextPlain: null,
        questionType: null,
        difficulty: null,
        categoryId: null,
        pointId: null,
        fileIds: null,
        correctAnswer: null,
        correctAnswerPlain: null,
        options: null
      },
      dynamicOptions: [],
      correctAnswer: '',
      rules: {
        questionTitle: [
          { required: true, message: "请输入题目标题", trigger: "blur" }
        ],
        questionText: [
          { required: true, message: "题干不能为空", trigger: "blur" }
        ],
        questionType: [
          { required: true, message: "请选择题型", trigger: "change" }
        ],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" }
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" }
        ],
        pointId: [
          { required: true, message: "请选择知识点", trigger: "change" }
        ],
        options: [
          {
            validator: (rule, value, callback) => {
              if (this.showOptionsArea && this.dynamicOptions.some(o => !o.label) &&
                this.form.questionType !== '4' && this.form.questionType !== '5') {
                callback(new Error("请填写所有选项内容"))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  computed: {
    showOptionsArea() {
      return ['1', '2', '3', '4', '5'].includes(this.form.questionType)
    },
    questionTypeComponent() {
      switch (this.form.questionType) {
        case '1': return 'SingleChoice';
        case '2': return 'MultipleChoice';
        case '3': return 'FillInBlank';
        case '4': return 'TrueFalse';
        case '5': return 'EssayQuestion';
        default: return '';
      }
    },
    showInputArea() {
      return ['1', '2', '3'].includes(this.form.questionType)
    }
  },
  watch: {
    questionId: {
      immediate: true,
      async handler(newVal) {
        if (newVal) {
          await this.loadQuestionData(newVal);
        } else {
          this.resetForm();
        }
      }
    }
  },
  methods: {
    async loadQuestionData(questionId) {
      try {
        const response = await getQuestions(questionId);
        this.form = response.data;

        // 初始化选项和答案
        this.correctAnswer = response.data.correctAnswer || '';
        this.dynamicOptions = [];

        if (response.data.options) {
          try {
            const optionsData = typeof response.data.options === 'string'
              ? JSON.parse(response.data.options)
              : response.data.options;
            if (optionsData?.items) {
              this.dynamicOptions = optionsData.items;
            }
          } catch (e) {
            console.error('解析options出错:', e);
          }
        }

        // 处理不同类型的答案回显
        if (this.form.questionType === '2') {
          const answers = (response.data.correctAnswer || '').split(',');
          this.dynamicOptions.forEach(option => {
            option.checked = answers.includes(option.value);
          });
        } else if (this.form.questionType === '3') {
          const answers = (response.data.correctAnswer || '').split(',');
          answers.forEach((answer, index) => {
            if (this.dynamicOptions[index]) {
              this.dynamicOptions[index].label = answer;
            }
          });
        } else if (this.form.questionType === '4') {
          this.correctAnswer = response.data.correctAnswer === '1' ? '正确' : '错误';
        }

        // 等待组件渲染
        await this.$nextTick();

        // 处理问答题的特殊逻辑
        if (this.form.questionType === '5' && this.$refs.questionComponent) {
          this.$refs.questionComponent.setContent(response.data.correctAnswer);

          if (this.form.fileIds) {
            const fileResponse = await getFilesByIds(this.form.fileIds);
            this.$refs.questionComponent.setFiles(fileResponse.data);
          }
        }

        // 更新分类和知识点
        if (this.$refs.categoryTree) {
          this.$refs.categoryTree.setCurrentKey(this.form.categoryId);
        }
        if (this.$refs.pointSelect) {
          await this.$nextTick();
          this.$refs.pointSelect.setCurrentValue(this.form.pointId);
        }

      } catch (error) {
        console.error('加载题目数据失败:', error);
        this.$message.error('加载题目数据失败');
      }
    },

    handleQuestionTypeChange() {
      this.$refs.form.clearValidate('options');
      this.dynamicOptions = [];
      this.correctAnswer = '';
      this.addOption();
    },

    addOption() {
      if (this.dynamicOptions.length >= 8) {
        this.$message.warning('最多添加8个填空');
        return;
      }
      const newOption = {
        label: '',
        value: String.fromCharCode(65 + this.dynamicOptions.length),
        checked: false
      };
      this.dynamicOptions.push(newOption);
    },

    removeOption(index) {
      this.dynamicOptions.splice(index, 1);
      this.dynamicOptions.forEach((item, idx) => {
        item.value = String.fromCharCode(65 + idx);
      });
    },

    updateOptions(options) {
      this.dynamicOptions = options;
    },

    updateCorrectAnswer(answer) {
      this.correctAnswer = answer;
    },

    handleEssayAnswerChange(content) {
      if (this.form.questionType === '5') {
        this.correctAnswer = content;
      }
    },

    handleCategoryChange(node) {
      this.form.categoryId = node ? node.categoryId : null;
      this.form.pointId = null;
    },

    handlePointChange(id) {
      this.form.pointId = id;
    },

    async submitForm() {
      try {
        await this.$refs.form.validate();

        // 处理答案数据
        if (this.form.questionType === '1') {
          this.form.correctAnswer = this.correctAnswer;
        } else if (this.form.questionType === '2') {
          this.form.correctAnswer = this.dynamicOptions
            .filter(o => o.checked)
            .map(o => o.value)
            .join(',');
        } else if (this.form.questionType === '3') {
          this.form.correctAnswer = this.dynamicOptions
            .map(o => o.label)
            .join(',');
        } else if (this.form.questionType === '4') {
          this.form.correctAnswer = this.correctAnswer === '正确' ? '1' : '0';
        } else if (this.form.questionType === '5') {
          this.form.correctAnswer = this.correctAnswer;
          if (this.$refs.questionComponent?.getPlainContent) {
            this.form.correctAnswerPlain = this.$refs.questionComponent.getPlainContent();
          }
          if (this.$refs.questionComponent?.getFileIds) {
            this.form.fileIds = this.$refs.questionComponent.getFileIds();
          }
        }

        // 处理选项数据
        if (this.showOptionsArea) {
          this.form.options = {
            type: this.form.questionType,
            items: this.dynamicOptions
          };
        }

        // 获取题干纯文本
        if (this.$refs.questionEditorComponent && this.$refs.questionEditorComponent.getPlainText) {
          this.form.questionTextPlain = this.$refs.questionEditorComponent.getPlainText();
        }

        const action = this.form.questionId
          ? updateQuestions(this.form)
          : addQuestions(this.form);

        await action;
        this.$message.success(this.form.questionId ? '修改成功' : '新增成功');
        this.$emit('success');
        this.resetForm();

      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error(error.message || '提交失败');
      }
    },

    resetForm() {
      this.$refs.form.resetFields();
      this.dynamicOptions = [];
      this.correctAnswer = '';
      this.form = {
        questionId: null,
        questionTitle: null,
        questionText: null,
        questionTextPlain: null,
        questionType: null,
        difficulty: null,
        categoryId: null,
        pointId: null,
        fileIds: null,
        correctAnswer: null,
        correctAnswerPlain: null,
        options: null
      };
    }
  }
};
</script>

<style scoped>
.options-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
